package auth

import (
	"errors"

	"github.com/golang-jwt/jwt/v5"
)

var secretKey = "sPib_tF49Vpm3JK9Iio8b_uXlSo7mpRPPVrNCKkJ3F4="

type ExtendClaims struct {
	UserId   uint32 `json:"uid"`
	UserName string `json:"unm"`
	RoleId   uint32 `json:"rid"`
}

type UserClaims struct {
	jwt.RegisteredClaims
	ExtendClaims
}

func (uc *UserClaims) GetExtendClaims() ExtendClaims {
	return uc.ExtendClaims
}

func GenerateToken(claims UserClaims) (string, error) {
	secret := []byte(secretKey)
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(secret)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

func JwtKeyFunc(token *jwt.Token) (any, error) {
	return []byte(secretKey), nil
}

func ParseToken(tokenString string) (*UserClaims, error) {
	if tokenString == "" {
		return nil, errors.New("token is empty")
	}
	token, err := jwt.ParseWithClaims(tokenString, &UserClaims{}, JwtKeyFunc)
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*UserClaims); ok && token.Valid {
		return claims, nil
	}
	return nil, errors.New("invalid token")
}
